﻿using HCQ2_Common.Attributes;
using HCQ2_Common.Constant;
using HCQ2_Model;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2_Model.WeiXinApiModel.ParamModel;
using HCQ2WebAPI_Logic.BaseAPIController;
using HCQ2WebAPI_Logic.Filters;
using HCQ2WebAPI_Logic.Model;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using HCQ2_Model.WeiXinApiModel.ResultApiModel;
using System;
using HCQ2_Model.VR.Params;
using HCQ2_Common.Encrypt;

namespace HCQ2WebAPI_Logic.DocumentController
{
    /// <summary>
    ///  VR头记通知、公告微信Service
    /// </summary>
    public class VRBoardChatAPIController: BaseWeiXinApiLogic
    {
        #region ✔1.1 获取广告信息 + WebApiResultJsonModel GetBoardInfo(BoardChartParam model)
        /// <summary>
        ///  获取广告信息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetBoardInfo(BoardChartParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<T_VRBoardAD> list = operateContext.bllSession.T_VRBoardAD.GetBoardByChart(model);
            List<VRBoardADModel> result = new List<VRBoardADModel>();
            list.ForEach(o =>
            {
                if (!string.IsNullOrEmpty(o.ad_url))
                    o.ad_url = o.ad_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                result.Add(o.toPOTO());
            });
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取广告信息列表~", result);
        }
        #endregion

        #region ✔1.1.1 获取广告详细信息 + WebApiResultJsonModel GetBoardDetailInfo(BoardDetailId model)
        /// <summary>
        ///  获取广告详细信息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetBoardDetailInfo(BoardDetailId model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_VRBoardAD board = operateContext.bllSession.T_VRBoardAD.Select(s => s.ad_id == model.ad_id).FirstOrDefault();
            if(board==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "查询的广告详细不存在！", null);
           VRBoardADModel result = new VRBoardADModel();
            if (!string.IsNullOrEmpty(board.ad_url))
                board.ad_url = board.ad_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            result = board.toPOTO();
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取广告详细信息~", result);
        }
        #endregion

        #region ✔1.2 获取检测单词列表 + WebApiResultJsonModel GetRandomWord(RandomWordParam param)
        /// <summary>
        ///  获取检测单词列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetRandomWord(RandomWordParam param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<RandomWordResult> result = operateContext.bllSession.T_VRBoardAD.GetRandomData(param);
            if (result == null || result.Count<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"课件关卡中的单词为空或者不够{param.num}条记录~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取检测单词列表~", result);
        }
        #endregion

        #region ✔1.3 保存单词检测结果 + WebApiResultJsonModel SaveDetectionResult(DetectionWodParam param)
        /// <summary>
        ///  保存单词检测结果
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel SaveDetectionResult(DetectionWodParam param)
        {
            int main_id = 0;
            try
            {
                if (!ModelState.IsValid)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
                int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(param.userid);
                //1.0 判断课件是否正常
                int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == param.file_id && !s.if_remove);
                if(mark<=0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "课件异常，课件不存在或已下架~", "");
                mark = operateContext.bllSession.T_VRCustomPass.SelectCount(s => s.file_id == param.file_id && s.cp_id == param.cp_id);
                if (mark <= 0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "关卡异常，关卡不存~", "");
                //1.0 保存主表信息
                T_VRHeadWordMain mWord = new T_VRHeadWordMain
                {
                    user_id = user_id,
                    file_id = param.file_id,
                    cp_id = param.cp_id,
                    date_len = param.date_len,
                    score = param.score,
                    create_date = DateTime.Now
                };
                //2.0 保存明细
                mark = operateContext.bllSession.T_VRHeadWordMain.Add(mWord);
                if(mark<=0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "添加检测记录失败~", "");
                main_id = mWord.wh_id;
                param.options.ForEach(s =>
                {
                    operateContext.bllSession.T_VRHeadWordDetailed.Add(new T_VRHeadWordDetailed
                    {
                        wh_id = mWord.wh_id,
                        word = s.word,
                        detletter = s.detletter,
                        choletter = s.choletter,
                        status = s.status,
                        score = s.score,
                        duration = s.duration,
                        create_date = DateTime.Now,
                        serial=s.serial
                    });
                });
            }
            catch (Exception ex)
            {
                if (main_id > 0)
                {
                    operateContext.bllSession.T_VRHeadWordMain.Delete(s => s.wh_id == main_id);
                    operateContext.bllSession.T_VRHeadWordDetailed.Delete(s => s.wh_id == main_id);
                }
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "添加出错~", ex.Message);
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功添加检测记录~", main_id);
        }
        #endregion

        #region ✔1.4 获取用户金币数量 + WebApiResultJsonModel GetGoldNumByUser(HCQ2_Model.APPModel.ParamModel.BaseAPI model)
        /// <summary>
        ///  获取用户金币数量
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [VRServiceValid]
        public WebApiResultJsonModel GetGoldNumByUser(HCQ2_Model.APPModel.ParamModel.BaseAPI model)
        {
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            if(user==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息不存在~", "");
            Dictionary<string, decimal> map = new Dictionary<string, decimal>();
            map.Add("buy_gold", user.buy_gold);//V金币数量
            map.Add("give_gold", user.give_gold);//赠送比数量
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取金币信息~", map);
        }
        #endregion

        #region ✔1.5 修改支付密码 + WebApiResultJsonModel ModifyPayPwd(PayPwdModel model)
        /// <summary>
        ///  修改支付密码
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ModifyPayPwd(PayPwdModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息不存在~", "");
            //判断原始支付密码是否正确
            if (!string.IsNullOrEmpty(user.pay_pwd))
            {
                string oriPwd = EncryptHelper.Md5Encryption(model.ori_pwd);
                if(!oriPwd.Equals(user.pay_pwd))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "原始支付密码不正确~", "");
            }
            //修改新支付密码
            operateContext.bllSession.T_User.Modify(new T_User { pay_pwd = EncryptHelper.Md5Encryption(model.new_pwd) }, s => s.user_id==user.user_id, "pay_pwd");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "支付密码修改成功~", "");
        }
        #endregion

        #region ✔1.6 获取已购商品数量 + WebApiResultJsonModel ModifyPayPwd(PayPwdModel model)
        /// <summary>
        ///  获取已购商品数量
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetPayGoodNum(PayGoodNumParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            if(user_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息不存在~", "");
            int numCount = operateContext.bllSession.T_VRBoardAD.GetPayGoodNum(model, user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取已购商品数量~", numCount);
        }
        #endregion
    }
}
